package com.bwie.parkdemo.mvvm.viewmodel;

import android.app.Application;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.TimeUtils;
import com.bwie.lib_core.base.BaseEntity;
import com.bwie.lib_core.mvvm.base.BaseViewModel;
import com.bwie.parkdemo.mvvm.model.AddRepairModel;
import com.bwie.parkdemo.mvvm.model.entity.AddRepairEntity;
import com.bwie.parkdemo.mvvm.model.entity.LoginEntity;
import com.bwie.parkdemo.mvvm.model.request_entity.AddRepairBindEntity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class AddRepairViewModel extends BaseViewModel<AddRepairModel> {

    public AddRepairBindEntity bindEntity;//界面databinding绑定相关数据
    public AddRepairItemListener itemListener;//当前界面中recycler Item点击事件
    public AddRepairListener listener;//当前界面按钮点击事件
    public List<Object>imges = new ArrayList<>();//本地图片地址
    public int adapterType = 2;//适配器码值
    private int repairId = 47;

    public AddRepairViewModel(@NonNull Application application) {
        super(application);
        itemListener = new AddRepairItemListener();
        listener = new AddRepairListener();
        bindEntity = new AddRepairBindEntity();
    }

    @Override
    protected AddRepairModel createModel() {
        return new AddRepairModel();
    }

    @Override
    protected void initData() {
        imges.add("+");
        //获取本地用户数据进行操作
        LoginEntity.Values values = m.requestUser(getApplication());
        bindEntity.dept_Id = values.dept_id;
        bindEntity.repairUserId = values.uId;
        bindEntity.setDepartmentName("技术部");
        bindEntity.setDescribe("水管漏水");
        bindEntity.setAppointData(TimeUtils.millis2String(System.currentTimeMillis(),new SimpleDateFormat("yyyy-MM-dd")));
        bindEntity.setRepairData(TimeUtils.millis2String(System.currentTimeMillis(),new SimpleDateFormat("yyyy-MM-dd")));
        bindEntity.setUserName(values.uName);
        bindEntity.setImges(imges);
    }

    //activity获取完成图片后添加到viewmodel的图片集合，通过单项绑定
    //刷新数据到recyclerview列表中
    public void addImgPath(String path){
        if (TextUtils.isEmpty(path))
            return;
        imges.add(0,path);
        bindEntity.setImges(imges);
    }

    //上传维修图片方法
    private void uploadImgs(){
        List<String>pathes = new ArrayList<>();
        for (Object object : imges){
            String path = (String) object;
            if (path.equals("+"))
                continue;
            pathes.add(path);
        }
        m.uploadImg(pathes)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                        showDialog();
                    }

                    @Override
                    public void onNext(BaseEntity baseEntity) {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("ZXWQ","uploadImgs:"+e.getMessage());
                        showMsg("请求出错:"+e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        disDialog();
                        addRepair();
                    }
                });
    }

    //添加维修申请方法
    private void addRepair(){
        Map<String,Object>map = new HashMap<>();
        map.put("departmentId",bindEntity.dept_Id);
        map.put("repairData",bindEntity.getRepairData());
        map.put("repairDescribe",bindEntity.getDescribe());
        map.put("repairTime",bindEntity.getAppointData());
        map.put("repairUserId",0);
        map.put("userId",bindEntity.dept_Id);
        String jsonStr = new Gson().toJson(map);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"),jsonStr);
        m.requestAddRepair(body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                        showDialog();
                    }

                    @Override
                    public void onNext(BaseEntity baseEntity) {
                        AddRepairEntity entity = (AddRepairEntity) baseEntity;
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("ZXWQ","uploadImgs:"+e.getMessage());
                        showMsg("请求出错:"+e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        disDialog();
                        //图片集合只有一个+
                        if (imges.size()==1) {
                            showMsg("上传成功");
                            finishAct();
                            return;
                        }
                        addRepairImgs();
                    }
                });
    }

    //维修申请与维修图片绑定方法
    private void addRepairImgs(){
        RequestBody[] bodyes = new RequestBody[imges.size()-1];
        int i = 0;
        for (Object object : imges){
            String path = (String) object;
            //图片列表尾部+，不需要上传
            if (path.equals("+"))
                continue;
            Map<String,Object>map = new HashMap<>();
            map.put("repairId",repairId);
            map.put("repairPath",path);
            String jsonStr = new Gson().toJson(map);
            RequestBody body = RequestBody.create(MediaType.parse("application/json"),jsonStr);
            bodyes[i]=body;
            i++;
        }
        m.request(bodyes).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                        showDialog();
                    }

                    @Override
                    public void onNext(BaseEntity baseEntity) {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("ZXWQ","uploadImgs:"+e.getMessage());
                        showMsg("请求出错"+e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        showMsg("维修申请添加成功");
                        finishAct();
                    }
                });
    }

    //点击提交按钮监听器
    public class AddRepairListener{
        //点击提交
        public void sendBtn(){
            //根据用户选择的问题描述图片数量来进行判断是否上传图片
            //需要上传图片时->先上传图片；在添加维修申请；在绑定维修申请的图片
            //不需要上传图片->添加维修申请
            if (imges.size()<=1){
                //未添加任何图片
                addRepair();
            }else {
                //集合中添加了对应的拍照图片
                uploadImgs();
            }
        }
    }

    //recyclerview点击监听器
    public class AddRepairItemListener implements BaseQuickAdapter.OnItemClickListener{

        @Override
        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            //当用户点击的为最后一条索引,+添加图片时使用eventbus发布事件到对应activity开启相机获取图片
            if (position == (imges.size()-1)){
                Log.e("ZXWQ","AddRepairItemListener");
                EventBus.getDefault().post(""+System.currentTimeMillis());
            }
        }
    }

}
